package com.immoc.jdbc.hrapp.command;

import java.sql.*;
import java.util.Scanner;

public class QueryCommand implements Command{
    @Override
    public void execute() {
        System.out.println("输入部门名称");
        Scanner in = new Scanner(System.in);
        String dName = in.nextLine();
        Connection conn = null;
        try{
            // 1. 加载注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 创建数据库链接
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/immoc?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai",
                    "root",
                    "455843572Lemonib"
            );
            // 3. 创建statement对象
//             Statement statement = conn.createStatement();
//             ResultSet rs = statement.executeQuery("SELECT * FROM employee WHERE dname='"+dName+"'");
            PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM employee WHERE dname=?");
            preparedStatement.setString(1,dName);
            ResultSet rs = preparedStatement.executeQuery();
            // 4. 遍历sql语句
            while(rs.next()){
                Integer eno = rs.getInt(1);
                String ename = rs.getString("ename");
                Float salary = rs.getFloat("salary");
                String dname = rs.getString("dname");
                System.out.println(eno + "-" + ename + "-" +dname + "-" + salary);
            }}catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                // 5. 关闭连接，释放资源
                if (conn != null && conn.isClosed() == false) {
                    conn.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
